package com.atwj.controller;

import com.atwj.Service.UserService;
import com.atwj.Service.impl.UserServiceImpl;
import com.atwj.entity.User;
import com.atwj.utils.webUtil;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

/**
 * @author 吴先森
 * @description: 用户管理
 * @create 2022-03-22 16:49
 */
public class UserServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();

    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        boolean existsUsername = userService.existsUsername(username);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("existsUsername", existsUsername);

        Gson gson = new Gson();
        String json = gson.toJson(resultMap);

        resp.getWriter().write(json);
    }


    /**
     * 处理账号注销
     *
     * @param req
     * @param resp
     * @author 吴先森
     * @date 2022/3/28 19:43
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //销毁session中用户登陆的信息（或者销毁Session）
        req.getSession().invalidate();
        //重定向到首页（或登陆页面）
        resp.sendRedirect(req.getContextPath());
    }


    /**
     * 处理登陆操作
     *
     * @param req
     * @param resp
     * @author 吴先森
     * @date 2022/3/22 17:10
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //        获取参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

//        调用Service中login()方法处理业务
        User login = userService.login(new User(null, username, password, null));

//        判断登陆结果
        if (login == null) {
//            吧错误信息和回显的表单项信息保存到Request域中
            req.setAttribute("msg", "用户名或密码错误");
            req.setAttribute("username", username);
//            失败 返回登陆页面
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
        } else {
            //登陆成功
            // 保存用户登录的信息到Session域中
            req.getSession().setAttribute("user", login);
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req, resp);
        }

    }


    /**
     * 处理注册操作
     *
     * @param req
     * @param resp
     * @author 吴先森
     * @date 2022/3/22 17:10
     */
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取 Session 中的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        // 删除 Session 中的验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        //        获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");

        User user = webUtil.copyParamToBean(req.getParameterMap(), new User());

//        检查验证码
        if (token != null && token.equalsIgnoreCase(code)) {
//            检查用户名是否正确
            if (userService.existsUsername(username)) {
//                不可用
                req.setAttribute("msg", "用户名已存在");
                req.setAttribute("username", username);
                req.setAttribute("email", email);
//                返回注册界面
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
            } else {
//                可用，成功注册，储存数据，保存到session域中
                userService.registUser(new User(null, username, password, email));
//                返回注册成功界面
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req, resp);
            }
        } else {
            req.setAttribute("msg", "验证码错误");
            req.setAttribute("username", username);
            req.setAttribute("email", email);

            System.out.println("验证码[" + code + "]错误");
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
        }
    }
}
